<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Promise封装ajax</title>
</head>

<body>
  <button id="btn">点击获取段子</button>
</body>
<script>
  window.onload = function () {
    const btn = document.getElementById('btn');

    const url = 'https://api.apiopen.top/api/sentences'

    btn.addEventListener('click', async () => {
      const res = await ajax('GET', url, (results) => {
        console.log(results);
      })
      console.log(res);
    })
    function ajax(type, url, fun) {
      return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest()
        xhr.open(type, url, true);
        xhr.responseType = 'json'
        xhr.send();
        xhr.onreadystatechange = function () {
          if (xhr.readyState !== 4) return
          if (xhr.status >= 200 && xhr.status < 300) {
            fun(xhr.response)
          } else {
            console.log('error');
          }
        }
      })
    }
  }
</script>

</html>